<?php
/**
 * create by phpstorm
 * User: 冰帝
 * Date: 2023/5/4
 * Remark: 登录接口
 * 现在的努力是为了小时候吹过的牛逼
 */

namespace app\api\controller;


use app\BaseController;
use app\common\model\User;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Cache;
use TencentCloud\Sms\V20210111\SmsClient;
// 腾讯云短信接口对应的Request类
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 腾讯云短信可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
class EmailLogin extends BaseController
{
    protected $ip;
    protected $device;
    /**\
     * @param $phone
     * 登录
     */
    public function login(){
        $phone=input('post.email');
        $code=input('post.code');
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        // 判断是否是iOS设备（iPhone/iPad）
        $this->device=$userAgent;
//        $invite_code=input('post.invite_code');
        $this->ip = $_SERVER['REMOTE_ADDR'];
//        //校验手机号验证法是否合法
        $code_redis=Cache::get($phone.$code);
        if($code!=$code_redis){
            return show(0,'验证码错误');
        }
//        if ($invite_code){
//            $p=\think\facade\Db::name('user')->where('invite_code',$invite_code)->find();
//            if ($p){
//                $pid=$p['id'];
//            }else{
//                $pid=0;
//            }
//        }else{
//            $pid=0;
//            $p=[];
//        }
        //判断手机号是否为新增还是登录
        $user = User::getByEmail($phone);
        if ($user) {
            $uid = $user['id'];
        } else {
            $uid = $this->newUser($phone);
            if ($uid == false) {
                return false;
            }
            $user['is_vip']=2;
        }
        //生成保存的数据
        $cachedValue = $this->prepareCachedValue($uid,$user['is_vip']);
        //保存缓存
        $token = $this->saveToCache($cachedValue);
        $data['token']=$token;
        $data['is_vip']=$user['is_vip'];
        return show(1,'',$data);
    }
    /**\
     * @param $openid
     * @return mixed
     * 去创建新用户
     */
    private function newUser($phone)
    {
        $abc = city($this->ip);
        $device = get_device($this->device);
        \think\facade\Db::startTrans();
        try {
            //生成邀请码
            $invite_code=get_invite_code();
            $user = \think\facade\Db::name('user')
                ->insertGetId([
                    'nickname' => "烟友_".mt_rand(1000,9999),
                    'email' => $phone,
                    'create_time' => time(),
                    'ip' => $this->ip,
                    'country' => $abc['nation'],
                    'province' => $abc['region'],
                    'city' => $abc['city'],
                    'is_vip'=>2,
                    'invite_code'=>$invite_code,
                    'vip_end_time'=>time()+604800,
                    'device_type'=>$device,
                    'register_type'=>"邮箱",
                ]);
            //如果是第一个赠送vip奖励
            $data[]=[
                'user_id'=>$user,
                'day'=>7,
                'create_time'=>time(),
                'type'=>1,
            ];
            \think\facade\Db::name('user_vip_record')
                ->insertAll($data);
            \think\facade\Db::commit();
            return $user;
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return false;
        }
    }

    /**\
     * @param $wxResult
     * @param $uid
     * @return mixed
     * 写入缓存的数据
     */
    private function prepareCachedValue($uid,$is_vip)
    {
        $cachedValue['uid'] = $uid;
        $cachedValue['is_vip'] = $is_vip;
        return $cachedValue;
    }

    //写入缓存
    private function saveToCache($cachedValue)
    {
        //32个字符组成一组随机字符串
        $randChars = md5(date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT));
        //用三组字符串,进行md5加密
        Cache::set($randChars,serialize($cachedValue),2592000);
        return $randChars;
    }
}